package com.lianjia.sh.tools.util;
import org.objectweb.asm.Type;
import org.springframework.asm.*;
import org.springframework.util.ClassUtils;

import java.io.InputStream;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 获取参数名：仅仅用于测试，抄自spring的ParameterNameDiscoverer
 * Created by yangsp1 on 16/6/28.
 */
public class ReflactUtil {
    /**
     * Helper class that inspects all methods (constructor included) and then
     * attempts to find the parameter names for that member.
     */
    private static class ParameterNameDiscoveringVisitor extends org.springframework.asm.ClassVisitor {

        private static final String STATIC_CLASS_INIT = "<clinit>";

        private final Class<?> clazz;

        private final Map<Member, String[]> memberMap;

        public ParameterNameDiscoveringVisitor(Class<?> clazz, Map<Member, String[]> memberMap) {
            super(SpringAsmInfo.ASM_VERSION);
            this.clazz = clazz;
            this.memberMap = memberMap;
        }

        @Override
        public org.springframework.asm.MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
            // exclude synthetic + bridged && static class initialization
            if (!isSyntheticOrBridged(access) && !STATIC_CLASS_INIT.equals(name)) {
                return new LocalVariableTableVisitor(clazz, memberMap, name, desc, isStatic(access));
            }
            return null;
        }

        private static boolean isSyntheticOrBridged(int access) {
            return (((access & org.springframework.asm.Opcodes.ACC_SYNTHETIC) | (access & org.springframework.asm.Opcodes.ACC_BRIDGE)) > 0);
        }

        private static boolean isStatic(int access) {
            return ((access & org.springframework.asm.Opcodes.ACC_STATIC) > 0);
        }
    }

    private static class LocalVariableTableVisitor extends org.springframework.asm.MethodVisitor {

        private static final String CONSTRUCTOR = "<init>";

        private final Class<?> clazz;

        private final Map<Member, String[]> memberMap;

        private final String name;

        private final org.springframework.asm.Type[] args;

        private final String[] parameterNames;

        private final boolean isStatic;

        private boolean hasLvtInfo = false;

        /*
         * The nth entry contains the slot index of the LVT table entry holding the
         * argument name for the nth parameter.
         */
        private final int[] lvtSlotIndex;

        public LocalVariableTableVisitor(Class<?> clazz, Map<Member, String[]> map, String name, String desc, boolean isStatic) {
            super(SpringAsmInfo.ASM_VERSION);
            this.clazz = clazz;
            this.memberMap = map;
            this.name = name;
            this.args = org.springframework.asm.Type.getArgumentTypes(desc);
            this.parameterNames = new String[this.args.length];
            this.isStatic = isStatic;
            this.lvtSlotIndex = computeLvtSlotIndices(isStatic, this.args);
        }

        @Override
        public void visitLocalVariable(String name, String description, String signature, org.springframework.asm.Label start, org.springframework.asm.Label end, int index) {
            this.hasLvtInfo = true;
            for (int i = 0; i < this.lvtSlotIndex.length; i++) {
                if (this.lvtSlotIndex[i] == index) {
                    this.parameterNames[i] = name;
                }
            }
        }

        @Override
        public void visitEnd() {
            if (this.hasLvtInfo || (this.isStatic && this.parameterNames.length == 0)) {
                // visitLocalVariable will never be called for static no args methods
                // which doesn't use any local variables.
                // This means that hasLvtInfo could be false for that kind of methods
                // even if the class has local variable info.
                this.memberMap.put(resolveMember(), this.parameterNames);
            }
        }

        private Member resolveMember() {
            ClassLoader loader = this.clazz.getClassLoader();
            Class<?>[] argTypes = new Class<?>[this.args.length];
            for (int i = 0; i < this.args.length; i++) {
                argTypes[i] = ClassUtils.resolveClassName(this.args[i].getClassName(), loader);
            }
            try {
                if (CONSTRUCTOR.equals(this.name)) {
                    return this.clazz.getDeclaredConstructor(argTypes);
                }
                return this.clazz.getDeclaredMethod(this.name, argTypes);
            }
            catch (NoSuchMethodException ex) {
                throw new IllegalStateException("Method [" + this.name +
                        "] was discovered in the .class file but cannot be resolved in the class object", ex);
            }
        }

        private static int[] computeLvtSlotIndices(boolean isStatic, org.springframework.asm.Type[] paramTypes) {
            int[] lvtIndex = new int[paramTypes.length];
            int nextIndex = (isStatic ? 0 : 1);
            for (int i = 0; i < paramTypes.length; i++) {
                lvtIndex[i] = nextIndex;
                if (isWideType(paramTypes[i])) {
                    nextIndex += 2;
                }
                else {
                    nextIndex++;
                }
            }
            return lvtIndex;
        }

        private static boolean isWideType(org.springframework.asm.Type aType) {
            // float is not a wide type
            return (aType == org.springframework.asm.Type.LONG_TYPE || aType == org.springframework.asm.Type.DOUBLE_TYPE);
        }
    }

        /**
         *
         * <p>
         * 比较参数类型是否一致
         * </p>
         *
         * @param types
         *            asm的类型({@link Type})
         * @param clazzes
         *            java 类型({@link Class})
         * @return
         */
        private static boolean sameType(Type[] types, Class<?>[] clazzes) {
            // 个数不同
            if (types.length != clazzes.length) {
                return false;
            }

            for (int i = 0; i < types.length; i++) {
                if (!Type.getType(clazzes[i]).equals(types[i])) {
                    return false;
                }
            }
            return true;
        }

        /**
         *
         * <p>
         * 获取方法的参数名
         * </p>
         *
         * @param m
         * @return
         */
        public static String[] getMethodParamNames(final Method mmmm) throws Exception {
            Method m = mmmm;
            Class clazz = m.getDeclaringClass();
            InputStream is = clazz.getResourceAsStream(ClassUtils.getClassFileName(clazz));

           org.springframework.asm.ClassReader classReader = new org.springframework.asm.ClassReader(is);
            Map<Member, String[]> map = new ConcurrentHashMap<Member, String[]>(32);
            classReader.accept(new ParameterNameDiscoveringVisitor(clazz, map), 0);
            for(Member member : map.keySet()){
                boolean isEqu = member.equals(m);
                System.out.println(isEqu);
            }
            return map.get(m);
        }

        public static void main(String[] args) throws Exception {
            String[] s = getMethodParamNames(ReflactUtil.class.getMethod(
                    "getMethodParamNames", Method.class));
            System.out.println(s);
            // 对String，Object，thread等jdk自带类型不起作
        }
}
